clear all;
clc;

tic
disp('Loading data...');
load 7nn30small;

k = 7;
lam = 1;
[n,s] = size(V);

l = 5000;

C = 10;
c = 10;

Y = yU(1:l)';

disp('Data loaded!');

Ivec = reshape(repmat((1:n)',1,k-1),[],1);
V = V(:,1:s);
n = size(V,1);
QC = V(Ivec,:) - V(IDXvec,:);
clear Ivec;
clear IDXvec;

nump = c*(c-1)/2;
sz = zeros(c,1);
idx = cell(10,1);
for i = 1:c
    idx{i}=find(Y==(i-1));
    sz(i)=size(idx{i},1);
end

ix = cell(c,c);
Y = cell(c,c);
P = cell(c,c);

for i = 1:c
    for j = i+1:c
        ix{i,j} = [idx{i};idx{j}];
        Y{i,j} = [ones(sz(i),1);-ones(sz(j),1)];
        P{i,j} = repmat(Y{i,j},1,s).*V(ix{i,j},:);
    end
end

Q = V(l+1:n,:);
clear V;

disp('Start optimization...');
tic

ct = 1;
cvx_begin sdp
cvx_solver sedumi
    variable t
    variable gam(s,nump)
    variable M(s,s) symmetric
    variable del(l,1) nonnegative
    variable bet(l,1) nonnegative
    variable bb(nump,1)
    minimize (t-lam*trace(M));
    for i = 1:c
        for j = i+1:c
            [M gam(:,ct);gam(:,ct)' t-2*C*ones(1,l)*del] >= 0;
            P{i,j}*gam(:,ct)+bb(ct)*Y{i,j}-ones(size(P{i,j},1),1)+del(ix{i,j})-bet(ix{i,j}) == 0;
            ct=ct+1;
        end
    end
    sum(QC*M.*QC,2) <= Dvec
    M == semidefinite(s);
cvx_end

toc

Yp = zeros(n-l,1);

for trn = 1:size(Q,1)
    vt = zeros(c,1);
    ct = 1;
    for i = 1:c
        for j = i+1:c
            if (Q(trn,:)*gam(:,ct)+bb(ct) > 0)
                vt(i)=vt(i)+1;
            else vt(j)=vt(j)+1;
            end
            ct=ct+1;
        end
    end
    [~,Yp(trn)] = max(vt);
end

Yp = int8(Yp)-1;

label = int8(yU(l+1:n)');
calacc(Yp,label)